package com.km.wskj.itmonitor.pager.wq;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.fingdo.statelayout.StateLayout;
import com.km.wskj.itmonitor.R;
import com.km.wskj.itmonitor.http.GlideImageLoader;
import com.km.wskj.itmonitor.http.ZxlGenericsCallback;
import com.km.wskj.itmonitor.model.FuncItem;
import com.km.wskj.itmonitor.model.KnowledgeLibrary;
import com.km.wskj.itmonitor.model.Slider;
import com.km.wskj.itmonitor.pager.base.LFragment;
import com.km.wskj.itmonitor.pager.login.LoginActivity;
import com.km.wskj.itmonitor.pager.news.NewsDetailActivity;
import com.km.wskj.itmonitor.pager.wq.forum.ForumActivity;
import com.km.wskj.itmonitor.pager.wq.knowledgelib.KnowledgeListActivity;
import com.km.wskj.itmonitor.pager.wq.note.NoteBookListActivity;
import com.km.wskj.itmonitor.pager.wq.parts.PartsActivity;
import com.km.wskj.itmonitor.pager.wq.wscollege.CollegeActivity;
import com.km.wskj.itmonitor.utils.StatusBarCompat;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.Transformer;
import com.youth.banner.listener.OnBannerClickListener;
import com.zxl.zxlapplibrary.util.LogUtils;
import com.zxl.zxlapplibrary.view.MyGridView;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

/**
 * @author by Xianling.Zhou on 2017/2/9.
 *         知识探索页面
 */
public class WqFragment extends LFragment {
    private static final String TAG = "WqFragment";
    //ui
    @BindView(R.id.tool_bar_title)
    TextView mTitle;
    @BindView(R.id.banner)
    Banner mBanner;
    @BindView(R.id.knowledge_container_gridview)
    LinearLayout mContainer;
    @BindView(R.id.sw_refresh)
    SwipeRefreshLayout mSwipeRefreshLayout;
    @BindView(R.id.state_layout)
    StateLayout stateLayout;

    //data
    List<FuncItem> funcItems = new ArrayList<>();
    private MyGridView gridView;
    private String pid = null;
    private List<KnowledgeLibrary> knowledgeLibrarys;

    //data
    private List<String> imgUrls;

    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_wq, container, false);
        ButterKnife.bind(this, view);

        stateLayout.setRefreshListener(new StateLayout.OnViewRefreshListener() {
            @Override
            public void refreshClick() {
                initBanner();
            }

            @Override
            public void loginClick() {

            }
        });
        initData();
        initBanner();
        initFuncItems();
        initRefresh();
        return view;
    }

    private void initRefresh() {
        // 不能在onCreate中设置，这个表示当前是刷新状态，如果一进来就是刷新状态，SwipeRefreshLayout会屏蔽掉下拉事件
        //swipeRefreshLayout.setRefreshing(true);
        // 设置颜色属性的时候一定要注意是引用了资源文件还是直接设置16进制的颜色，因为都是int值容易搞混
        // 设置下拉进度的背景颜色，默认就是白色的
        mSwipeRefreshLayout.setProgressBackgroundColorSchemeResource(android.R.color.white);
        // 设置下拉进度的主题颜色
        mSwipeRefreshLayout.setColorSchemeResources(R.color.colorWs_blue, R.color.colorPrimary, R.color.colorPrimaryDark);
        // 下拉时触发SwipeRefreshLayout的下拉动画，动画完毕之后就会回调这个方法
        mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                // 开始刷新，设置当前为刷新状态
                //swipeRefreshLayout.setRefreshing(true);
                // 加载完数据设置为不刷新状态，将下拉进度收起来
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        initBanner();
                        normalToasty("刷新成功");
                        mSwipeRefreshLayout.setRefreshing(false);
                    }
                }, 500);
            }
        });
    }

    /**
     * 初始化轮播器
     */
    private void initBanner() {
        stateLayout.showLoadingView();

        pdc.bannerList(HTTP_TASK_TAG, new ZxlGenericsCallback<List<Slider>>() {
            @Override
            public void onError(Call call, Exception e, int i) {
                LogUtils.e(TAG, e);
                stateLayout.showErrorView();
            }

            @Override
            public void onResponse(final List<Slider> sliders, int i) {
                imgUrls = new ArrayList<>();

                for (Slider slider : sliders
                        ) {
                    imgUrls.add(slider.host + slider.filePath + slider.newFileName);
                }

                //设置图片加载器
                mBanner.setImageLoader(new GlideImageLoader());
                //设置图片集合
                mBanner.setImages(imgUrls);
                //设置轮播器样式
                mBanner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR);
                //设置动画
                mBanner.setBannerAnimation(Transformer.DepthPage);
                //设置自动轮播，默认为true
                mBanner.isAutoPlay(true);
                //设置轮播时间
                mBanner.setDelayTime(3000);
                //设置指示器位置（当banner模式中有指示器时）
                mBanner.setIndicatorGravity(BannerConfig.CENTER);
                //banner设置方法全部调用完毕时最后调用
                mBanner.start();
                //轮播器点击事件
                mBanner.setOnBannerClickListener(new OnBannerClickListener() {
                    @Override
                    public void OnBannerClick(int position) {
                        Intent t = new Intent(getActivity(), NewsDetailActivity.class);
                        t.putExtra("slider", sliders.get(position - 1));
                        startActivity(t);
                    }
                });

                stateLayout.showContentView();
            }
        });


    }

    /**
     * 初始化数据
     */
    private void initData() {
        mTitle.setText("微栖");
        pdc.knowledgeLib(HTTP_TASK_TAG, pid, new ZxlGenericsCallback<List<KnowledgeLibrary>>() {
            @Override
            public void onError(Call call, Exception e, int i) {
                LogUtils.e(TAG, e);
            }

            @Override
            public void onResponse(List<KnowledgeLibrary> knowledgeLibraries, int i) {
                knowledgeLibrarys = knowledgeLibraries;
            }
        });

    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mContainer.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                mContainer.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                createGridView();
            }
        });
    }


    private void initFuncItems() {
        String s[] = getResources().getStringArray(R.array.knowledge_func_title_array);
        String index[] = getResources().getStringArray(R.array.knowledge_func_index);
        int r[] = {R.mipmap.monitor_application
                , R.mipmap.monitor_database
                , R.mipmap.monitor_middle_ware
                , R.mipmap.monitor_internet
                , R.mipmap.monitor_server
                , R.mipmap.monitor_memory
                , R.mipmap.yjs
                , R.mipmap.xxaq
                , R.mipmap.monitor_round
                , R.mipmap.hyfa
                , R.mipmap.hyfa
                , R.mipmap.bzgf
        };

        funcItems.clear();

        for (int i = 0; i < s.length && i < r.length; i++) {
            FuncItem fi = new FuncItem();
            fi.name = s[i];
            fi.resId = r[i];
            fi.index = index[i];
            funcItems.add(fi);
        }
    }


    private void createGridView() {
        gridView = new MyGridView(getActivity(), new MyGridView.MyGridViewAdapter() {
            @Override
            public int rowspacing(MyGridView myGridView) {
                return 0;
            }

            @Override
            public int colspacing(MyGridView myGridView) {
                return 0;
            }

            @Override
            public int leftpadding(MyGridView myGridView) {
                return 0;
            }

            @Override
            public int toppadding(MyGridView myGridView) {
                return 0;
            }

            @Override
            public int colCount(MyGridView myGridView) {
                return 4;
            }

            @Override
            public int rowHeight(MyGridView myGridView) {
                return mContainer.getHeight() / 3;
            }

            @Override
            public int viewWidth(MyGridView myGridView) {
                return mContainer.getWidth();
            }

            @Override
            public int count(MyGridView myGridView) {
                return funcItems.size();
            }

            @Override
            public View cell(int i, MyGridView myGridView) {
                View view = getActivity().getLayoutInflater().inflate(R.layout.monitor_item_func, null);
                ImageView iv_pic = (ImageView) view.findViewById(R.id.iv_pic);
                TextView tv_name = (TextView) view.findViewById(R.id.tv_name);
                LinearLayout bg = (LinearLayout) view.findViewById(R.id.ll_minitor_bg);


                FuncItem fi = funcItems.get(i);
                iv_pic.setImageResource(fi.resId);
                tv_name.setText(fi.name);
                return view;
            }

            @Override
            public View title(int i, MyGridView myGridView) {
                return null;
            }

            @Override
            public int titleOffsetY(MyGridView myGridView) {
                return 0;
            }

            @Override
            public boolean needGridLine(MyGridView myGridView) {
                return false;
            }
        });


        gridView.setListener(new MyGridView.MyGridViewListener() {
            @Override
            public void onCellTouchDown(int i) {

            }

            @Override
            public void onCellTouchUp(int i) {

            }

            @Override
            public void onCellLongPress(int i) {

            }

            @Override
            public void onCellClick(int i) {

                switch (i) {
                    //操作系统
                    case 0: {
                        String id = getCurrentItem("操作系统");
                        Intent t = new Intent(getActivity(), KnowledgeListActivity.class);
                        t.putExtra("id", id);
                        t.putExtra("itemName", "操作系统");
                        startActivity(t);
                    }
                    break;
                    //数据库
                    case 1: {
                        String id = getCurrentItem("数据库");
                        Intent t = new Intent(getActivity(), KnowledgeListActivity.class);
                        t.putExtra("id", id);
                        t.putExtra("itemName", "数据库");
                        startActivity(t);

                    }
                    break;
                    //中间件
                    case 2: {
                        String id = getCurrentItem("中间件");
                        Intent t = new Intent(getActivity(), KnowledgeListActivity.class);
                        t.putExtra("id", id);
                        t.putExtra("itemName", "中间件");
                        startActivity(t);

                    }
                    break;
                    //网络
                    case 3: {
                        String id = getCurrentItem("网络");
                        Intent t = new Intent(getActivity(), KnowledgeListActivity.class);
                        t.putExtra("id", id);
                        t.putExtra("itemName", "网络");
                        startActivity(t);

                    }
                    break;
                    //服务器
                    case 4: {
                        String id = getCurrentItem("服务器");
                        Intent t = new Intent(getActivity(), KnowledgeListActivity.class);
                        t.putExtra("id", id);
                        t.putExtra("itemName", "服务器");
                        startActivity(t);

                    }
                    break;
                    //存储
                    case 5: {
                        String id = getCurrentItem("存储");
                        Intent t = new Intent(getActivity(), KnowledgeListActivity.class);
                        t.putExtra("id", id);
                        t.putExtra("itemName", "存储");
                        startActivity(t);
                    }
                    break;
                    //云计算
                    case 6: {
                        String id = getCurrentItem("云计算");
                        Intent t = new Intent(getActivity(), KnowledgeListActivity.class);
                        t.putExtra("id", id);
                        t.putExtra("itemName", "云计算");
                        startActivity(t);
                    }
                    break;
                    //信息安全
                    case 7: {
                        String id = getCurrentItem("信息安全");
                        Intent t = new Intent(getActivity(), KnowledgeListActivity.class);
                        t.putExtra("id", id);
                        t.putExtra("itemName", "信息安全");
                        startActivity(t);
                    }
                    break;
                    //机房动态
                    case 8: {
                        String id = getCurrentItem("机房动环");
                        Intent t = new Intent(getActivity(), KnowledgeListActivity.class);
                        t.putExtra("id", id);
                        t.putExtra("itemName", "机房动环");
                        startActivity(t);
                    }
                    break;

                    //系统集成
                    case 9: {
                        String id = getCurrentItem("系统集成");
                        Intent t = new Intent(getActivity(), KnowledgeListActivity.class);
                        t.putExtra("id", id);
                        t.putExtra("itemName", "系统集成");
                        startActivity(t);
                    }
                    break;

                    //行业方案
                    case 10: {
                        String id = getCurrentItem("行业方案");
                        Intent t = new Intent(getActivity(), KnowledgeListActivity.class);
                        t.putExtra("id", id);
                        t.putExtra("itemName", "行业方案");
                        startActivity(t);
                    }
                    break;

                    //标准规范
                    case 11: {
                        String id = getCurrentItem("标准规范");
                        Intent t = new Intent(getActivity(), KnowledgeListActivity.class);
                        t.putExtra("id", id);
                        t.putExtra("itemName", "标准规范");
                        startActivity(t);
                    }
                    break;
                }
            }
        });
        LinearLayout.LayoutParams p = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        mContainer.addView(gridView.getView(), p);
    }

    private String getCurrentItem(String itemName) {
        if (knowledgeLibrarys != null && knowledgeLibrarys.size() > 0)
            for (KnowledgeLibrary klb : knowledgeLibrarys
                    ) {
                if (klb.columnName.equals(itemName))
                    return klb.id;
            }
        return null;
    }

    @Override
    public void onStart() {
        //开始轮播
        mBanner.startAutoPlay();
        super.onStart();
    }

    @Override
    public void onStop() {
        //结束轮播
        mBanner.stopAutoPlay();
        super.onStop();
    }

    @Override
    public void onDestroyView() {
        //结束轮播
        mBanner.stopAutoPlay();
        imgUrls.clear();
        super.onDestroyView();
    }

    @OnClick({R.id.ll_forum, R.id.ll_notebook, R.id.ll_ws_college, R.id.ll_parts})
    public void onClick(View view) {
        switch (view.getId()) {
            //技术专区
            case R.id.ll_forum:
                startActivity(new Intent(getContext(), ForumActivity.class));
                break;
            //云笔记
            case R.id.ll_notebook:
                if (pdc.mCurrentUser == null) {
                    normalToasty("请先登录");
                    startActivity(new Intent(getContext(), LoginActivity.class));
                    return;
                }
                startActivity(new Intent(getContext(), NoteBookListActivity.class));
                break;
            //微数学院
            case R.id.ll_ws_college:
                startActivity(new Intent(getContext(), CollegeActivity.class));
                break;
            //配件专区
            case R.id.ll_parts:
                startActivity(new Intent(getContext(), PartsActivity.class));
                break;
        }
    }
}
